package com.jumi.microservice.service.comment;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.domain.GoodsSkuInfoDTO;
import com.jumi.microservice.dto.comment.admin.CommentHideRequest;
import com.jumi.microservice.dto.comment.admin.CommentListRequest;
import com.jumi.microservice.dto.comment.admin.CommentListResponse;
import com.jumi.microservice.dto.comment.admin.CommentReplyRequest;
import com.jumi.microservice.dto.comment.commentEnum.CommentEnum;
import com.jumi.microservice.dto.reponse.UserExternalResponse;
import com.jumi.microservice.entity.Comment;
import com.jumi.microservice.mapper.CommentMapper;
import com.jumi.microservice.service.CommodityApi;
import com.jumi.microservice.service.IMemberService;
import com.jumi.microservice.service.IUserExternalService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Scw
 * @Date 2020-08-04 17:56
 */
@Service
public class AdminCommentService {
    private static final Logger log = LoggerFactory.getLogger(AdminCommentService.class);
    @Resource
    private CommentMapper commentMapper;
    @DubboReference
    private CommodityApi goodsClient;
    @DubboReference
    private IUserExternalService iUserExternalService;
    @DubboReference
    private IMemberService iMemberService;

    /**
     * 评论列表
     *
     * @param commentListRequest
     * @return
     */
    public TableDataInfo<CommentListResponse> commentsAdminList(CommentListRequest commentListRequest) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        /*敏感词查询*/
        if (commentListRequest.getSensitiveWords() != null && !"".equals(commentListRequest.getSensitiveWords())) {
            queryWrapper.like("content", commentListRequest.getSensitiveWords());
        }
        /*商品名搜索*/
        log.debug("\n\n\n\n\n---------评论列表[商品名搜索]:[{}]", JSON.toJSONString(commentListRequest.getGoodName()));
        if (commentListRequest.getGoodName() != null && !"".equals(commentListRequest.getGoodName())) {
            //根据商品查询商品id 返回
            String goodName = commentListRequest.getGoodName().trim();
            /*调用商品接口返回商品id*/
            Map<Long, String> getGoodsSkuIdByName = goodsClient.getGoodsSkuIdByName(goodName);
            if (getGoodsSkuIdByName != null) {
                Set<Long> skuIds = getGoodsSkuIdByName.keySet();
                log.info("评论列表------【调用商品接口返回商品skuIds】:[{}]", JSON.toJSONString(skuIds));
                if (!skuIds.isEmpty()) {
                    queryWrapper.in("gid", skuIds);
                } else {
                    return new TableDataInfo<>();
                }
            }
        }
        //创建开始时间
        if (commentListRequest.getBeginTime() != null && !"".equals(commentListRequest.getBeginTime())) {
            queryWrapper.ge("create_time", commentListRequest.getBeginTime().replace("T00:00:00", "") + " 00:00:00");
        }
        //创建结束时间
        if (commentListRequest.getEndTime() != null && !"".equals(commentListRequest.getEndTime())) {
            queryWrapper.le("create_time", commentListRequest.getEndTime().replace("T00:00:00", "") + " 23:59:59");
        }

        if (commentListRequest.getProductSatisfaction() != null) {
            List<Integer> satisAverage = new ArrayList<Integer>();

            switch (commentListRequest.getProductSatisfaction()) {
                case 1:
                    satisAverage.add(1);
                    queryWrapper.in("product_satisfaction", satisAverage);//差评
                    break;
                case 2:
                    satisAverage.add(2);
                    satisAverage.add(3);
                    queryWrapper.in("product_satisfaction", satisAverage);
                    break;
                case 3:
                    satisAverage.add(4);
                    satisAverage.add(5);
                    queryWrapper.in("product_satisfaction", satisAverage);
                    break;
                default:
                    break;
            }
        }
        IPage<Comment> page = new Page<>(commentListRequest.getPageNum(), commentListRequest.getPageSize());
        page = commentMapper.selectPage(page, queryWrapper);
        List<Comment> commentPage = page.getRecords();
        log.debug("评论列表------【commentPage】:[{}]", JSON.toJSONString(commentPage));
        //有序列表
        List<CommentListResponse> result = new ArrayList<>();
        if (commentPage == null||commentPage.size()==0) {
            return new TableDataInfo<>();
        }
        //根据商品ID--sku查询商品主图【商品服务提供接口】
        List<Long> skuIds = new ArrayList<>();
        List<GoodsSkuInfoDTO> getGoodsSkuInfoByIds = new ArrayList<>();
        for (Comment comments : commentPage) {
            skuIds.add(comments.getGid().longValue());
        }
        if (skuIds.size() > 0) {
            log.debug("评论列表------【sku查询商品主图】:[{}]", JSON.toJSONString(skuIds));
            getGoodsSkuInfoByIds = goodsClient.getGoodsSkuInfoByIds(skuIds);
        }
        log.debug("评论列表------【根据商品ID--sku查询商品主图】:[{}]", JSON.toJSONString(getGoodsSkuInfoByIds));
        for (Comment comments : commentPage) {
            String userName = comments.getUserName();
            if (userName == null || userName.equals("")) {
                //查询用户名
                Integer uid = comments.getUid().intValue();
                if (uid != null) {
                    UserExternalResponse userExternalResponse = iUserExternalService.getUserByUid(uid);
                    log.debug("后台评论列表----【用户的所有信息】:[{}]", JSON.toJSONString(userExternalResponse));
                    if (userExternalResponse != null) {
                        userName = userExternalResponse.getNickName();
                        comments.setUserName(userName);
                    }
                }
            }

            CommentListResponse commentListResponse = new CommentListResponse();
            BeanUtils.copyProperties(comments, commentListResponse);

            //设置商品名称
            if (getGoodsSkuInfoByIds != null) {
                getGoodsSkuInfoByIds.forEach(
                        getGoodsSkuInfo -> {
                            if (comments.getGid().longValue() == getGoodsSkuInfo.getId()) {
                                commentListResponse.setGidTitle(getGoodsSkuInfo.getGoodsName());
                                log.debug("后台评论列表----【GidTitle】:[{}]", JSON.toJSONString(commentListResponse.getGidTitle()));
                            }
                        }
                );

            }
            log.debug("后台评论列表----【commentListResponse】:[{}]", JSON.toJSONString(commentListResponse));
            result.add(commentListResponse);
        }
        TableDataInfo<CommentListResponse> dataInfo = new TableDataInfo<>();
        dataInfo.setRows(result);
        dataInfo.setTotal(page.getTotal());
        return dataInfo;

    }

    /**
     * 是否隐藏
     *
     * @param '0':否              1是
     * @param commentHideRequest
     * @return
     */
    public Boolean editHide(CommentHideRequest commentHideRequest) {
        boolean result = false;
        Integer commentId = commentHideRequest.getId();
        if (commentId == null) {
            throw new BaseException(CommentEnum.COMMENT_HIDEN_ID_ERROR.getCode(), CommentEnum.COMMENT_HIDEN_ID_ERROR.getMessage());
        } else {
            Comment comment = new Comment();
            BeanUtils.copyProperties(commentHideRequest, comment);

            int row = commentMapper.updateById(comment);
            if (row > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;
    }

    /**
     * 回复内容
     *
     * @param commentReplyRequest
     * @return
     */
    public Boolean editReply(CommentReplyRequest commentReplyRequest) {
        boolean result = false;

        Integer commentId = commentReplyRequest.getId();
        if (commentId == null) {
            throw new BaseException(CommentEnum.COMMENT_HIDEN_ID_ERROR.getCode(), CommentEnum.COMMENT_HIDEN_ID_ERROR.getMessage());
        } else {
            String reply = commentReplyRequest.getReply().trim();
            log.debug("评论列表------【回复内容】:[{}]", JSON.toJSONString(reply));
            //字数限制
            if (reply.length() > 200 || reply == null) {
                throw new BaseException(CommentEnum.COMMENT_REPLY_LONG.getCode(), CommentEnum.COMMENT_REPLY_LONG.getMessage());
            }

            Comment comment = new Comment();
            BeanUtils.copyProperties(commentReplyRequest, comment);

            int row = commentMapper.updateById(comment);
            if (row > 0) {
                //返回 状态
                result = true;
            }
        }
        return result;

    }


}
